/**************************************************************************//**
 * @item     CosyOS-II Kernel
 * @file     sv_int_loc.c
 * @brief    中断本地服务（仅在用户中断中调用，并在本地执行）
 * @author   迟凯峰
 * @version  V1.0.0
 * @date     2023.10.20
 ******************************************************************************/

#include "os_var.h"
#include "os_api.h"

#if SYSCFG_MCUCORE == 8051
#pragma NOAREGS
#endif



/*
 * 飞信（接收飞信）
 */
#if SYSCFG_FETION == __ENABLED__

m_fetion_t si_recv_fetion(m_fetion_t _OBJ_MEM_ *ft)
{
	m_fetion_t fetion = *ft;
	*ft = false;
	return fetion;
}

#endif



/*
 * 消息邮箱（接收邮件）
 */
#if SYSCFG_MAILBOX == __ENABLED__

#if SYSCFG_MCUCORE == 8051

s_bool_t si_can_read_gmbox(void _OBJ_MEM_ *gm)
{
	if(s_sign_write_mbox_accessor
	|| s_mbox_accessor == NULL || s_mbox_accessor->gm != gm){
		return true;
	}
	return false;
}

#if SYSCFG_MAILBOX_ACCESSMECHANISM == 1

s_bool_t si_can_read_lmbox(void)
{
	if(!s_mbox_accessor->lf) return false;
	s_mbox_accessor->lf = false;
	return true;
}

void *si_get_lmbox(void)
{
	return s_mbox_accessor->lm;
}

#endif

#else

s_bool_t si_recv_mail(void *lm, void *gm, size_t size, s_bool_t *gf) MCUCFG_251_REENTRANT
{
	if(s_mbox_accessor == NULL || s_mbox_accessor->gm != gm){
		if(*gf){
			*gf = false;
			s_memcpy(lm, gm, size);
			return true;
		}
		return false;
	}
	#if SYSCFG_MAILBOX_ACCESSMECHANISM == 1
	else if(s_mbox_accessor->lf){
		s_mbox_accessor->lf = false;
		s_memcpy(lm, s_mbox_accessor->lm, size);
		return true;
	}
	#endif
	return false;
}

#endif

#endif



/*
 * 消息队列（接收消息）
 */
#if SYSCFG_MSGQUEUE == __ENABLED__

#if SYSCFG_MCUCORE == 8051

s_bool_t si_can_access_msgqueue(s_msgqueue_tsp queue)
{
	if(!queue->mutex) goto __RET_FALSE;
	queue->mutex = false;
	if(queue->type == __DYNAMIC__){
		#if SYSCFG_DEBUGGING == __ENABLED__
		s_fault.error_recvmsg_int = true;
		#endif
		goto __FREE_MUTEX;
	}
	if(!queue->counter) goto __FREE_MUTEX;
	return true;
	
__FREE_MUTEX:
	queue->mutex = true;
	
__RET_FALSE:
	return false;
}

static void *_recv_msg_(s_bool_t _OBJ_MEM_ *mut, void *msg)
{
	*mut = true;
	return msg;
}

void *si_recv_msg(s_msgqueue_tsp queue)
{
	void *msg;
	sRecvMsg_Static(msg);
	return _recv_msg_((s_bool_t *)&queue->mutex, msg);
}

#else

void *si_recv_msg(s_msgqueue_tsp queue)
{
	void *msg = NULL;
	if(!queue->mutex) return NULL;
	queue->mutex = false;
	if(queue->type == __DYNAMIC__){
		#if SYSCFG_DEBUGGING == __ENABLED__
		s_fault.error_recvmsg_int = true;
		#endif
	}
	else if(!queue->counter);
	else{
		sRecvMsg_Static(msg);
	}
	queue->mutex = true;
	return msg;
}

#endif

#endif



/*
 * 全局变量（读全局变量）
 */
#if SYSCFG_MCUCORE != 8051

void *si_read_gvar(void *gv)
{
	if(s_gvar_accessor == NULL || s_gvar_accessor->gv != gv){
		return gv;
	}
	return s_gvar_accessor->lv;
}

#endif
